package org.mayuanxiaonong.timserver.config;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SystemConfig {

	private static final Logger log = LoggerFactory.getLogger(SystemConfig.class);
	private static SystemConfig instance = null;
	private String baseDir = null;
	private String confDir = null;
	private ApplicationContext context = null;

	public static final String DEFAULT_BASE_DIR = "..";
	public static final String DEFAULT_CONF_DIR = "conf";
	public static final String DEFAULT_LIB_DIR = "lib";

	public static SystemConfig getInstance() {
		if (instance == null) {
			synchronized (SystemConfig.class) {
				if (instance == null) {
					instance = new SystemConfig();
				}
			}
		}
		return instance;
	}

	private SystemConfig() {
		loadSystemConfig();
	}

	private void loadSystemConfig() {
		baseDir = System.getProperty("base.dir", DEFAULT_BASE_DIR);
		confDir = new File(baseDir, DEFAULT_CONF_DIR).getAbsolutePath();

		context = new ClassPathXmlApplicationContext("spring-config.xml");
	}

	public String getBaseDir() {
		return baseDir;
	}

	public void setBaseDir(String baseDir) {
		this.baseDir = baseDir;
	}

	public String getConfDir() {
		return confDir;
	}

	public void setConfDir(String confDir) {
		this.confDir = confDir;
	}

	public Object getBean(String beanName) {
		return context.getBean(beanName);
	}

	@SuppressWarnings("unchecked")
	public <T> T getBean(Class<T> clazz) {
		String className = clazz.getSimpleName();
		String beanName = className.toLowerCase().charAt(0)
				+ className.substring(1);
		return (T) getBean(beanName);
	}

}
